import http from '@/utils/http'

export const lessonLoader = {
  data() {
    return {
      lesson: null,
      audio: null,
      loading: true,
      error: null
    }
  },
  
  methods: {
    async loadLesson(lessonId) {
      try {
        const coursePath = this.$route.params.coursePath
        // Load lesson details and content in a single API call with course path
        const lessonResponse = await http.get(`/lessons/${coursePath}/${lessonId}`)
        this.lesson = lessonResponse

        // 获取音频文件的base64编码
        const audioResponse = await http.get(`/lessons/${coursePath}/audio/${lessonId}`)
        // 将base64编码转换为blob
        const byteCharacters = atob(audioResponse)
        const byteNumbers = new Array(byteCharacters.length)
        for (let i = 0; i < byteCharacters.length; i++) {
          byteNumbers[i] = byteCharacters.charCodeAt(i)
        }
        const byteArray = new Uint8Array(byteNumbers)
        const blob = new Blob([byteArray], { type: 'audio/mpeg' })
        this.audio = new Audio(URL.createObjectURL(blob))
        
        // Only add event listeners if component has the corresponding methods
        if (this.onAudioEnded) {
          this.audio.addEventListener('ended', this.onAudioEnded)
        }
        if (this.onAudioTimeUpdate) {
          this.audio.addEventListener('timeupdate', this.onAudioTimeUpdate)
        }

        this.loading = false
        
        // Call component-specific initialization if it exists
        if (this.initExercise) {
          this.initExercise()
        }
      } catch (err) {
        this.error = 'Failed to load lesson content'
        this.loading = false
        console.error('Error loading lesson:', err)
      }
    }
  }
}